package com.dpj.reentranloock_test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class AlternatePrint {
    public static void main(String[] args) throws InterruptedException {
        AwaitSignal awaitSignal = new AwaitSignal(5);
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();
        new Thread(()->{
            try {
                awaitSignal.print("a",a,b);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                awaitSignal.print("b",b,c);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                awaitSignal.print("c",c,a);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        Thread.sleep(1000);

        awaitSignal.lock();
        try {
            a.signal();
        }finally {
            awaitSignal.unlock();
        }

    }
}

class AwaitSignal extends ReentrantLock{
    private  int loopNumber;

    public AwaitSignal(int loopNumber) {
        this.loopNumber = loopNumber;
    }
    //参数1:打印内容   参数2:进入哪一休息间等待   参数3:下一间休息室
    public  void print(String str,Condition current,Condition next) throws InterruptedException {
        for (int i = 0; i <loopNumber ; i++) {
                lock();
                try {
                    current.await();
                    System.out.println(str);
                    next.signal();
                }finally {
                  unlock();
                }
        }
    }
}
